package com.project.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dtyunxi.rest.RestCode;
import com.dtyunxi.rest.RestResponse;
import com.dtyunxi.util.JacksonUtil;
import com.dtyunxi.util.WeiXinApi;
import com.project.common.Constants;
import com.project.entity.enumcommon.UserTypeEnum;
import com.project.entity.sms.CommAppVo;
import com.project.entity.sms.SmsMessageVo;
import com.project.entity.user.User;
import com.project.service.IUserService;
import com.project.util.EhcacheUtil;
import com.project.util.EncryptUtil;
import com.project.util.GenerateCode;
import com.project.util.HttpRequest;
import com.project.util.WeiXinUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("api/login")
@Api(value = "api/login", description = "登录管理")
public class LoginController {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private IUserService userService;
	
	@ApiOperation(value = "发送短信验证码", notes = "发送短信验证码", response = String.class)
	@RequestMapping(value = "/sms/send", method = RequestMethod.POST)
	public RestResponse sendSmsMsg(
			@ApiParam(required = true, name = "mobile", value = "手机号")@RequestParam String mobile){
		// 生成随机验证码
		String randomCode = GenerateCode.randomCode(6);
		//发送短信
		CommAppVo commAppVo = new CommAppVo(Constants.SMS_APPID, Constants.SMS_APPSECRET);
		SmsMessageVo smsMessageVo = new SmsMessageVo();
		smsMessageVo.setTaget(mobile);
		smsMessageVo.setSendPoint(Constants.SMS_SEND_VERIFYCODE);
		smsMessageVo.setSignType(Constants.SMS_SING_YUNXI_KJ);
		smsMessageVo.addValue("verifycode", randomCode);
		String params = "commAppVo="+JacksonUtil.toJson(commAppVo)+"&smsMessageVo="+JacksonUtil.toJson(smsMessageVo);
		logger.info("发送短信验证码 sendSmsMsg. mobile:{}, randomCode:{}, params:{}",mobile,randomCode,params);
		String result = HttpRequest.sendPost(Constants.QINQU_GATEWAY_SEND_SMS_PATH,params);
		logger.info("发送短信验证码 返回. result:{}",result);
		if(result.contains("success")){
//			//验证码放缓存
			EhcacheUtil.put(Constants.VERIFY_CODE_CACHE, Constants.VERIFY_CODE+mobile, randomCode);
			return new RestResponse(RestCode.RESULT_SUCCESS,"发送成功");
		}
		return new RestResponse(RestCode.RESULT_SYSTEM_ERROR,"发送失败");
	}
	
	public static void main(String[] args) {
//		1、活动审核后的短信模版：
//		尊敬的{1}先生/女士，您报名的“{3}”活动已审核，结果为：{6}。相关说明：{8}。
//
//		2、  活动开始24小时前的短信模版
//		尊敬的{1}先生/女士，您参加的“{3}”活动即将开始，请准时参加活动。活动时间：{4}，活动地点：{6}。
//
//		3、入会审核后的短信模版
//		尊敬的{1}先生/女士，您提交的私董会入会申请已审核，结果为：{6}。相关说明：{8}。
		String SMS_USERNAME = "username"; // ${1}
		String SMS_ORDERCODE = "ordercode";// ${2}
		String SMS_SERVICENAME = "servicename";// ${3}
		String SMS_SERVICETIME = "servicetime";// ${4}
		String SMS_VERIFYCODE = "verifycode";// ${5}
		String SMS_REASON = "reason";// ${6}
		String SMS_OTHER = "other";//{8}
//		String p = "commAppVo={\"appId\":\"20160901qinqu\",\"appSecret\":\"28e6ea65fa3b2e068ea5cbd9bb5edd6e\"}"
//				+ "&smsMessageVo={\"targets\": [\"13725312375\"], \"sendPoint\": \"SMS_SEND_VERIFYCODE\",\"signType\":\"云徙科技\""
//				+ ", \"mapValue\": {\"verifycode\": \"444444\"}}";
		String p = "commAppVo={\"appId\":\"20160901qinqu\",\"appSecret\":\"28e6ea65fa3b2e068ea5cbd9bb5edd6e\"}"
				+ "&smsMessageVo={\"targets\": [\"13725312375\"], \"sendPoint\": \"SMS_SEND_ACTIVITY_REMINDER\",\"signType\":\"云徙科技\""
				+ ", \"mapValue\": {\"username\": \"zero\",\"servicename\": \"测试活动2017\",\"servicetime\": \"审核通过\",\"other\": \"你太帅了\"}}";
		System.out.println(p);
		String string = HttpRequest.sendPost("http://qinqu.dtyunxi.cn/91qinqu-gateway/api/v1/pub/sms/send",p);
//		String string = HttpRequest.sendPost("http://120.76.30.235:8105/91qinqu-gateway/api/v1/pub/sms/send",p);
//		String string = HttpRequest.sendPost("http://stg.micservice.91qinqu.com/91qinqu-gateway/api/v1/pub/sms/send",p);
		System.out.println(string);
	}

	@ApiOperation(value = "登录用户", notes = "登录用户", response = String.class)
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public RestResponse login(
			@ApiParam(required = true, name = "mobile", value = "手机号")@RequestParam String mobile,
			@ApiParam(required = true, name = "verifyCode", value = "验证码")@RequestParam String verifyCode){
		String cacheVerifyCode =(String) EhcacheUtil.get(Constants.VERIFY_CODE_CACHE, Constants.VERIFY_CODE+mobile);
		logger.info("-----------------缓存中的验证码：{}",cacheVerifyCode);
		if(cacheVerifyCode==null || !cacheVerifyCode.equals(verifyCode))
			return new RestResponse(RestCode.RESULT_SYSTEM_ERROR,"验证码已失效或者不正确");
		String auth = "";
		synchronized (mobile) {
			User user = userService.getByUserCode(mobile);
			if(user==null){
				user = new User();
				user.setUserCode(mobile);
				user.setMobile(mobile);
				user.setRegistrationTime(new Date());
				user.setLastLoginTime(new Date());
				user.setUserType(UserTypeEnum.REGISTERED.getValue());
				userService.save(user);
			}else{
				user.setLastLoginTime(new Date());
				userService.update(user);
			}
			auth = EncryptUtil.MD5Encrypt(JacksonUtil.toJson(user),user.getUserCode());
			logger.info("-----------------return auth：{}",auth);
			EhcacheUtil.put(Constants.LOGIN_USER_CACHE, auth, user);
			EhcacheUtil.remove(Constants.VERIFY_CODE_CACHE, Constants.VERIFY_CODE+mobile);
		}
		return new RestResponse(auth);
	}
	
	@ApiOperation(value = "登出用户", notes = "登出用户", response = String.class)
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public RestResponse logout(HttpServletRequest request,HttpServletResponse response){
		logger.info("-----------------登出用户logout.requestMethod:{}----------------",request.getMethod());
		//只要是带自定义header的跨域请求，在发送真实请求前都会先发送OPTIONS请求，
		//浏览器根据OPTIONS请求返回的结果来决定是否继续发送真实的请求进行跨域资源访问。所以复杂请求肯定会两次请求服务端。
		if(!"OPTIONS".equalsIgnoreCase(request.getMethod())){
			String auth = request.getHeader("auth");
			if(StringUtils.isNotBlank(auth)){
				logger.info("-----------------登出用户成功logout success.auth:{}----------------",auth);
				EhcacheUtil.remove(Constants.LOGIN_USER_CACHE, auth);
				request.getSession().removeAttribute(Constants.CURRENT_LOGIN_USER);
			}else{
				logger.info("------------------auth为空,没有登录，返回401------------------");
				return new RestResponse(401,"no login",null);
			}
		}
		return RestResponse.SUCCESS;
	}
	

}
